<template>
	<view class="flex flex-direction padding-top-xl padding-lr-lg">
		<!-- <view class="flex flex-direction align-center justify-center margin-top-xl solids-bottom padding-bottom-xl">
			<image src="../../static/logo.png" class="img"></image>
			<view class="margin-top text-lg text-bold">门窗联盟</view>
		</view>

		<view class="margin-top-xl padding-left-lg">
			<view class="text-bold text-xl">您即将登录门窗联盟小程序</view>
			<view class="text-grey margin-top-sm">· 使用你的账号登录该应用</view>
		</view> -->

		<!-- <button type="primary" class="margin-top-xl btn" open-type="getUserInfo" @click="onGetUserInfo">微信授权</button> -->

		<button type="primary" hover-start-time="100" @click="openSetting" v-if="setting==0">登录</button>
		<view v-else>
			<button type="primary" hover-start-time="100" @tap="getuserinfo">登录</button>
		</view>

	</view>
</template>

<style lang="less">
	page {
		background-color: #fff;

		.img {
			width: 200rpx;
			height: 200rpx;
		}

		.btn {
			width: 100%;
		}
	}
</style>


<script>
	import avatar from '@/components/avatar.vue';
	import iconList from '@/components/iconList.vue';
	import authorize from '../../service.js';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	var _self;

	export default {
		data() {
			return {
				setting: 2 //0拒绝授权 1已经授权 2未操作 
			}
		},
		onLoad() {
			this.onGetUserInfo()
			_self = this;

		},
		onShow() {
			authorize.getSetting().then(setting => {
				this.setting = setting;
				console.log('setting', this.setting); // 0拒绝 or 1同意 or 2未操作
			})
		},
		methods: {
			openSetting: function() {
			    uni.showModal({
			     title: '提示',
			     content: '您已拒绝我们使用您的公开信息，请点击确定重新授权进行登录',
			     confirmText: '去设置',
			     success: function(res) {
			      if (res.confirm) {
			       uni.openSetting({
			        success(res) {
			         uni.getSetting({
			          success(res) {
			           let authSetting = res.authSetting
			           if (authSetting['scope.userInfo']) {
			            _self.status = 1;
			            uni.showToast({
			             icon: 'none',
			             title: '设置成功',
			             duration: 2000
			            });
			           }
			          }
				
			         })
			        }
			       })
			      } else if (res.cancel) {
			       console.log('用户点击取消');
			      }
			     }
			    });
			   },
			getuserinfo: function() {
				uni.showLoading({
					title: '登录中..',
					mask: true
				});
				let provider_code = {};
				authorize.getProvider().then(provider => {
					provider_code.provider = provider;
					return authorize.getCode(provider);
				}).then((code) => {
					provider_code.code = code;
					return Promise.resolve(provider_code.provider);
				}).then(provider => {
					return authorize.getUserInfo(provider);
				}).then(e => {
					let params = {
						code: provider_code.code,
						encryptedData: e.data,
						iv: e.iv,
						head_url: e.userInfo.avatarUrl,
						gender: e.userInfo.gender,
						nickname: e.userInfo.nickName
					};
					return authorize.login(params);
				}).then(isFirstLogin => {
					uni.setStorageSync('opid',isFirstLogin)
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: '登录成功',
						duration: 2000
					});
					// 返回上一页面
					setTimeout(function() {
						uni.navigateBack({
							delta: 1
						});
					}, 1000);
				}).catch(err => {
					uni.hideLoading();
					//拒绝授权
					if (err == 0) {
						_self.status = 0;
						uni.showToast({
							icon: 'none',
							title: '您已拒绝授权，请重新登陆授权我们使用您的公开信息',
							duration: 2000
						});
						return;
					}
					uni.showToast({
						icon: 'none',
						title: '登陆失败，请稍候再试',
						duration: 2000
					});
					console.log(err);
				})
			},
			openSetting: function() {
				uni.showModal({
					title: '提示',
					content: '您已拒绝我们使用您的公开信息，请点击确定重新授权进行登录',
					confirmText: '去设置',
					success: function(res) {
						if (res.confirm) {
							uni.openSetting({
								success(res) {
									uni.getSetting({
										success(res) {
											let authSetting = res.authSetting
											if (authSetting['scope.userInfo']) {
												_self.status = 1;
												uni.showToast({
													icon: 'none',
													title: '设置成功',
													duration: 2000
												});
											}
										}
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			...mapMutations(['login']),
			/* 
				获取个人信息
			 */
			onGetUserInfo() {
				uni.getUserInfo({
					success: (res) => {
						console.log(res)
						this.exchangeOpenId(res.userInfo);
					}
				})
			},
			/*
			   换取openid
			*/
			exchangeOpenId(data) {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						wx.request({
							url: 'https://wechat.lccmart.com/ygy/api/wechatapi/get_openid',
							data: {
								code: res.code
							},
							success: (info) => {
								const {
									avatarUrl,
									nickName
								} = data;
								const openid = info.data.openid;
								console.log(openid)
								this.$store.commit('login',openid)
								uni.setStorageSync('isFirstLogin', 'true');
								uni.request({
									url: 'https://wechat.lccmart.com/ygy/api/wechatapi/wechat_login',
									data: {
										openid: openid,
										nickname: nickName,
										photo: avatarUrl
									},
									success: (res) => {
										console.log(res)
									}
								})
								uni.switchTab({
									url: '../index/index'
								})
							}
						})
					}
				})
			},
		}
	}
</script>
